package com.cgwx.common.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @Description 创建线程池工具类
 */
public class ThreadFactoryUtil {

    // 基于数组的阻塞队列
    private static BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(100);

    private ThreadFactoryUtil() {

    }

    public static ThreadPoolExecutor getThreadFactoryUtilInstance(int threadNum) {
        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("splitlist-pool-%d").build();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(threadNum, threadNum, 3L,
                TimeUnit.SECONDS, blockingQueue, factory,
                // 自定义策略
                (r, executor) -> {
                    try {
                        if (!executor.isShutdown()) {
                            while (executor.getQueue().remainingCapacity() == 0) {
                                System.out.println("队列已满，线程数量达到最大数量！");
                                executor.getQueue().put(r);
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("塞入队列异常");
                    }
                    System.out.println("塞进队列成功！");
                });
        pool.allowCoreThreadTimeOut(true);
        return pool;
    }
}
